package com.googlecode.weathergram;

import android.app.Service;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class GeoLocationService extends Service implements LocationListener {

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		initService();
		return START_NOT_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		initService();
		return binder;
	}

	public class GeoLocationBinder extends Binder {
		public Location getCurrentLocation() {
			return location;
		}
	}

	private static final long CHANGE_MIN_DISTANCE = 100; // 100 meters
	private static final long CHANGE_MIN_TIME = 1000 * 30; // 30 sec

	private IBinder binder = new GeoLocationBinder();

	private LocationManager locationManager;
	private Location location;

	private Criteria criteria;

	public GeoLocationService() {
	}

	private void initService() {
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_MEDIUM);
		String provider = locationManager.getBestProvider(criteria, false);
		// String provider = LocationManager.NETWORK_PROVIDER;

		locationManager.requestLocationUpdates(provider, CHANGE_MIN_TIME,
				CHANGE_MIN_DISTANCE, this);
		location = locationManager.getLastKnownLocation(provider);
		Log.i(getClass().getSimpleName(), "Service initialized");
	}

	@Override
	public void onLocationChanged(Location location) {
		Log.i(getClass().getSimpleName(), "updating Location");
		this.location = location;
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

}
